<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends BaseController {
    public function __construct() {
        parent::__construct();

        // 移动端初始化方法
        $this->wx_init();
        
        // 加载库
        $this->load->model('schoolModel');
        $this->load->model('contentModel');
        $this->load->model('wxAppliModel');
        $this->load->model('wxUserModel');
        $this->load->model('workflowModel');
        $this->load->model('classesModel');
    }

    public function index() {
        $this->load->model('accountModel');
        $this->load->model('staffModel');
        $this->htmlTitle = '首页';
        // 获取所有应用
        $params['bindUserType'] = $this->bindUserType;
        $params['isDelete'] = 0;
        // 排序
        $params['orderBy'] = 'sort_level DESC';
        // 关联后台admin_menu表
        // 外链的admin_menu_id=0
        $adminMenuIdArr = array();
        // 支持管理员
        if($this->bindUserType == BIND_TYPE_STUDENT || ($this->bindUserType == BIND_TYPE_TEACHER && $this->user['user_type'] == USER_TYPE_SCHOOL)) {
            // 学生：后台学校功能权限对应
            $schoolInfo = $this->schoolModel->get_school_info($this->user['school_id']);
            $adminMenuIdArr = explode(',', $schoolInfo['school_module_set']);
        } else {
            // 教师：后台教师角色组功能权限对应
            $roleIdSet = $this->user['role_id_set'];
            $roleIdArr = explode(',', $roleIdSet);
            // 获取学校角色列表
            $roleList = $this->staffModel->get_role_list($this->user['school_id']);
            // 使用id作为键值
            $roleList = array_value_to_key($roleList, 'id');
            foreach($roleIdArr as $roleId) {
                if(isset($roleList[$roleId])) {
                    $menuSet = $roleList[$roleId]['role_menu'];
                    if($menuSet) {
                        $menuArr = explode(',', $menuSet);
                        $adminMenuIdArr = array_merge($adminMenuIdArr, $menuArr);
                    }
                }
            }
            
            $schoolInfo = $this->schoolModel->get_school_info($this->user['school_id']);
            $schoolAdminMenuIdArr = explode(',', $schoolInfo['school_module_set']);
            // 判断是否在学校权限里
            foreach($adminMenuIdArr as $key => $id) {
                if(!in_array($id, $schoolAdminMenuIdArr)) {
                    unset($adminMenuIdArr[$key]);
                }
            }
        }

        // 判断是否显示防疫
        // 获取健康管理菜单信息
        $healthMenu = $this->accountModel->get_menu_info_by_name('健康管理');
        if($healthMenu) {
            if(in_array($healthMenu['id'], $adminMenuIdArr)) {
                $this->showHealth = true;
            } else {
                $this->showHealth = false;
            }
        } else {
            $this->showHealth = false;
        }

        array_push($adminMenuIdArr, '0');
        $params['adminMenuIdArr'] = array_unique($adminMenuIdArr);
        $params['excludeTitleArr'] = array();
        if(!DEBUG && $this->user['school_id'] == '23') {
            // 湖南新瀚高中去除‘对话留言’
            $params['excludeTitleArr'] = array('对话留言');
        }
        // 没开通教师考勤的学校去掉‘教师考勤’菜单
        if(empty($schoolInfo) || $schoolInfo['enable_teacher_sign'] == 0) {
            $params['excludeTitleArr'][] = '教师考勤';
        }
        // 没开通闸机的学校去掉‘闸机记录’菜单
        $gateParams['schoolId'] = $schoolInfo['id'];
        $gateParams['isDelete'] = 0;
        $gateList = $this->schoolModel->get_gate_list($gateParams);
        if(empty($gateList)) {
            $params['excludeTitleArr'][] = '闸机记录';
        }
        $applications = $this->wxAppliModel->get_wx_application_list($params);
        // 处理自定义外链
        foreach($applications as $key => $value) {
            if($value['custom_menu_id'] != 0) {
                $customMenu = $this->schoolModel->get_custom_menu_info($value['custom_menu_id']);
                if($customMenu['is_delete'] || $customMenu['school_id'] != $this->user['school_id']) {
                    // 去掉外链
                    unset($applications[$key]);
                } else {
                    // var_export($customMenu);exit;
                    $applications[$key]['link'] = $customMenu['link'];
                    $applications[$key]['title'] = $customMenu['title'];
                    $applications[$key]['icon'] = $customMenu['icon'];
                }
            }
        }
        // 获取当前用户应用
        $params['userId'] = $this->user['id'];
        $userAppli = $this->wxAppliModel->get_wx_user_appli($params);
        $userAppliIdArr = array();
        if($userAppli['appli_ids']) {
            // 用户已添加过
            $userAppliIdArr = explode(',', $userAppli['appli_ids']);
            // 兼容之前可以8个
            if(count($userAppliIdArr) === 8) {
                array_pop($userAppliIdArr);
            }
        } else {
            // 如未添加过，默认已添加前7个应用
            foreach($applications as $key => $application) {
                if($key < 7) {
                    array_push($userAppliIdArr, $application['id']);
                }
            }
        }
        // 用户已添加应用列表
        $addList = array();
        // 按sort_level倒序
        foreach($applications as $application) {
            if(in_array($application['id'], $userAppliIdArr)) {
                array_push($addList, $application);
            }
        }
        $this->addList = $addList;
        // echo '<pre>';var_export($userAppliIdArr);exit;
        // 获取轮播图
        $bannerParams['isDelete'] = 0;
        $bannerParams['schoolId'] = $this->user['school_id'];
        if(isset($this->user['campus_id'])) {
            $bannerParams['campusId'] = $this->user['campus_id'];
        }
        $this->bannerList = $this->wxAppliModel->get_banner_list($bannerParams);
        // 待办事项
        $itemsUnread = array();
        // 获取学生待办事项
        if($this->bindUserType == BIND_TYPE_STUDENT) {
            // 未读作业
            $homeworkUnread = $this->_get_homework_unread();
            foreach($homeworkUnread['items'] as &$item) {
                // 设置未读类型
                // $item['typeRead'] = READ_TYPE_HOMEWORK;
                // 设置未读标签
                $item['typeLabel'] = '作业';
                // 设置title
                $item['title'] = $item['homework_title'];
                // 设置content
                $item['content'] = $item['homework_content'];
                // 更新时间去掉秒
                $item['updatetime'] = time_remove_second($item['updatetime']);
                //设置详情路由
                $item['detailLink'] = wx_url('classes/homework_detail/') . $item['id'];
                array_push($itemsUnread, $item);
            }
        }
        // 获取教师待办事项
        if($this->bindUserType == BIND_TYPE_TEACHER) {
            // 未读邮件
            $mailUnread = $this->_get_mail_unread();
            foreach($mailUnread['items'] as &$item) {
                // 设置未读类型
                // $item['typeRead'] = READ_TYPE_MAIL;
                // 设置未读标签
                $item['typeLabel'] = '邮件';
                // 设置title
                $item['title'] = $item['mail_title'];
                // 设置content
                $item['content'] = $item['mail_content'];
                // 更新时间去掉秒
                $item['updatetime'] = time_remove_second($item['updatetime']);
                //设置详情路由
                // $item['detailLink'] = wx_url('home/unread_detail/') . $item['id'] . '?type=' . READ_TYPE_MAIL;

                array_push($itemsUnread, $item);
            }
            // 未读申请审批
            $applicationUnread = $this->_get_application_unread();
            foreach($applicationUnread['items'] as &$item) {
                // 设置未读类型
                // $item['typeRead'] = READ_TYPE_APPLICATION;
                // 设置未读标签
                $item['typeLabel'] = '申请审批';
                $content = $item['content'];
                $contentArr = json_decode($content, true);
                $appliTitle = '';
                $appliContent = '';
                if($contentArr) {
                    foreach($contentArr as $content) {
                        // 获取申请标题
                        if($content['type'] === 'workflow-text' && strstr($content['label'], '标题')) {
                            $appliTitle .= $content['value'];
                        }
                        // 获取申请内容
                        if($content['type'] === 'workflow-content') {
                            $appliContent .= $content['value'];
                        }
                    }
                }
                // 设置title
                $item['title'] = $appliTitle;
                // 设置content
                $item['content'] = $appliContent;
                // 更新时间去掉秒
                $item['updatetime'] = time_remove_second($item['updatetime']);
                //设置详情路由
                // $item['detailLink'] = wx_url('home/unread_detail/') . $item['id'] . '?type=' . READ_TYPE_APPLICATION;

                array_push($itemsUnread, $item);
            }
        }
        // 按时间排序
        $timeKey =  array_column($itemsUnread, 'updatetime');
        array_multisort($timeKey, SORT_DESC, $itemsUnread);
        // 设置待办事项
        $this->itemsUnread = $itemsUnread;
        
        // 获取jssdk参数
        $this->load->library('wechat');
        $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        $this->dataJssdk = $this->wechat->jssdk_data($url);

        // 卡号过期处理
        if($this->user['expired']) {
            $list = $this->wxAppliModel->get_wx_application_list(array(
                'bindUserType' => BIND_TYPE_STUDENT,
                'includeTitleArr' => array('班级通知', '校园公告')
            ));
            $this->addList = $list;
        }

        $this->display(WX_DIR . DIRECTORY_SEPARATOR . "index");
    }

    // 查看待办事项
    public function unread_detail($id) {
        // echo "<script>alert('功能暂未开放');history.go(-1);</script>"; 
        // exit; 

        $type = $this->get('type');
        if($type == READ_TYPE_MAIL) {
            $this->htmlTitle = "邮件详情";
            $this->mailInfo = $this->contentModel->get_mail_info($id);
            // 转换updatetime为格式：2019.10.10
            $this->mailInfo['updatetimeFormat'] = format_time_to_date($this->mailInfo['updatetime']);
            // 插入已读记录
            $this->_mark_read(READ_TYPE_MAIL, $id, $this->user, $this->bindUserType);
            $this->display(WX_DIR . DIRECTORY_SEPARATOR . "mail_detail");
        }
        if($type == READ_TYPE_APPLICATION) {
            $this->htmlTitle = "申请审批详情";
            $this->appliInfo = $this->workflowModel->get_workflow_application_info($id);
            // 转换updatetime为格式：2019.10.10
            $this->appliInfo['updatetimeFormat'] = format_time_to_date($this->appliInfo['updatetime']);
            // 插入已读记录
            $this->_mark_read(READ_TYPE_APPLICATION, $id, $this->user, $this->bindUserType);
            $this->display(WX_DIR . DIRECTORY_SEPARATOR . "application_detail");
        }
    }

    // 防疫上传页面
    public function health_edit() {
        // $this->htmlTitle = '健康自查上报';
        $this->htmlTitle = '防疫上报';
        $this->healthData = get_health_const_data();
        // 获取学校所有地区
        $this->load->library('area');
        $this->citys = $this->area->get_all_areas();
        // 判断是否已提交过
        // $healthInfo = $this->wxUserModel->get_wx_user_health_info_by_user_id($this->user['id'], $this->bindUserType);
        $healthInfo = array();
        if($healthInfo) {
            // 获取症状数组
            $symptomkeyArr = explode(',', $healthInfo['symptom']);
            // 获取症状字符数组
            $symptomArr = array();
            if($symptomkeyArr) {
                foreach($symptomkeyArr as $symptomkey) {
                    if($symptomkey) {
                       array_push($symptomArr, $this->healthData['symptom'][$symptomkey]);
                    }
                }
                $healthInfo['symptomStr'] = implode(',', $symptomArr);
            }
            $this->health = $healthInfo;
        }
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . "health_edit");
    }

    // 保存健康信息操作
    public function save_health_action() {
        $id = $this->post('id');
        $region = trim($this->post('region'));
        $regionDesc = trim($this->post('regionDesc'));
        $isReturn = $this->post('isReturn') ? 1 : 0;
        $isContact = $this->post('isContact') ? 1 : 0;
        $isDetained = $this->post('isDetained') ? 1 : 0;
        $currentStatus = $this->post('currentStatus');
        $familyStatus = $this->post('familyStatus');
        $symptom = $this->post('symptom');
        $treatment = $this->post('treatment');
        // var_export($symptom);exit;
        if(empty($region) && !empty($regionDesc)) {
            throw new Exception('请先选择地区');
        }
        // 获取任课班级列表
        if($this->bindUserType == BIND_TYPE_TEACHER) {
            // 教师权限
            $teacherClassArr = $this->get_classes_by_teacher_id(true);
            if($teacherClassArr) {
                if(count($teacherClassArr) === 1) {
                    $classNameStr = $teacherClassArr[0]['class_name'];
                } else {
                    $classNameStr = $teacherClassArr[0]['class_name'] . '、' . $teacherClassArr[1]['class_name'];
                    if(count($teacherClassArr) > 2) {
                        $classNameStr .= '...';
                    }
                }
                $classNameStr = $classNameStr;
            } else {
                $classNameStr = '';
            }
        }

        $data = array(
            'school_id' => $this->user['school_id'],
            'user_id' => $this->user['id'],
            'bind_user_type' => $this->bindUserType,
            'class_ids' => $this->bindUserType == BIND_TYPE_STUDENT ? $this->user['class']['id'] : $this->user['class_ids'],
            'class_names' => $this->bindUserType == BIND_TYPE_STUDENT ? $this->user['class']['class_name'] : $classNameStr,
            'realname' => $this->user['realname'],
            'mobile' => $this->user['mobile'],
            'holiday_dest' => $region,
            'holiday_dest_desc' => $regionDesc,
            'is_return' => $isReturn,
            'is_contact' => $isContact,
            'is_detained' => $isDetained,
            'current_status' => $currentStatus,
            'family_status' => $familyStatus,
            'symptom' => $symptom,
            'treatment' => $treatment,
            'updatetime' => date('Y-m-d H:i:s'),
        );
        if(empty($id)) {
            // 插入
            $data['createtime'] = date('Y-m-d H:i:s');
            $this->db->insert(WxUserModel::$wxUserHealthTable, $data);
        } else {
            // 更新
            $this->db->update(WxUserModel::$wxUserHealthTable, $data, array('id' => $id));
        }
        $id = $this->db->insert_id();
        // 发送模板消息
        if($this->bindUserType == BIND_TYPE_STUDENT) {
            // 获取预警字段列表
            $warnDataArr = $this->wxUserModel->get_wx_user_health_warn_list(array(
                'schoolId' => $this->user['school_id']
            ));
            $isWarn = false;
            foreach($warnDataArr as $warn) {
                $warnKey = $warn['key'];
                $warnVal = $warn['value'];
                $warnValArr = explode(',', $warnVal);
                $healthVal = $data[$warnKey];
                $healthValArr = explode(',', $healthVal);
                foreach($healthValArr as $val) {
                    if(in_array($val, $warnValArr)) {
                        $isWarn = true;
                    }
                    continue;
                }
            }
            if($isWarn) {
                // // 获取该学生的任课老师列表
                // $params['schoolId'] = $this->user['school_id'];
                // $params['classId'] = $this->user['class_id'];
                // $params['isDelete'] = 0;
                // $list = $this->schoolModel->get_teacher_list($params);
                // 改成执教关系
                // 获取执教关系列表
                $coachParams['classId'] = $this->user['class_id'];
                $this->load->model('staffModel');
                $coachList = $this->staffModel->get_coach_list($coachParams);
                // 获取教师列表
                $teacherParams['isDelete'] = 0;
                $teacherParams['schoolId'] = $this->user['school_id'];
                $list = $this->schoolModel->get_teacher_list($teacherParams);
                // 使用id作为键
                $list = array_value_to_key($list, 'id');
                $teacherList = array();
                foreach($coachList as $coach) {
                    $teacherId = $coach['teacher_id'];
                    if(isset($list[$teacherId]) && !in_array($list[$teacherId], $teacherList)) {
                        array_push($teacherList, $list[$teacherId]);
                    }
                }
                if($teacherList) {
                    $this->load->library('wxtemplate');
                    $url = wx_url('pub/health_info_check/') . $id;
                    $tempData = array(
                        'first' => array(
                            'value' => '您好，收到新的预警通知。'
                        ),
                        'keyword1' => array(
                            'value' => '疫情防控预警'
                        ),
                        'keyword2' => array(
                            'value' => $data['createtime']
                        )
                    );
                    // 发送模板消息给任课老师
                    foreach($teacherList as $teacher) {
                        $this->wxtemplate->send_template_msg_for_user($teacher['id'], BIND_TYPE_TEACHER, WX_TEMPLATE_HEALTH, $tempData, $url);        
                    }
                }
            }
        }
        exit(json('提交成功', true));
    }

     // 防疫统计页面
     public function health_check_classes() {
        $this->htmlTitle = '防疫统计';
        // 任课班级
        $this->teacherClassArr = array();
        // 只供教师权限
        $this->teacherClassArr = $this->get_classes_by_teacher_id();
        if(count($this->teacherClassArr) === 1) {
            header('Location:' . wx_url('home/health_check?class_id=') . $this->teacherClassArr[0]['id']);
        } else {
            // 多个班级跳转到选择班级页面
            $this->display(WX_DIR . DIRECTORY_SEPARATOR . "health_check_classes");
        }

    }

     // 防疫统计页面
     public function health_check() {
        $classId = $this->get("class_id");
        if(empty($classId)) {
            throw new Exception('请先选择班级');
        }
        $classInfo = $this->classesModel->get_class_info($classId);
        if(empty($classInfo)) {
            throw new Exception('班级不存在');
        }
        $this->classId = $data['classId'] = $classId;
        $this->htmlTitle = $classInfo['class_name'] . '防疫统计';
        // 任课班级
        $this->teacherClassArr = array();
        // 只供教师权限
        $this->teacherClassArr = $this->get_classes_by_teacher_id();

        if(empty($this->teacherClassArr)) {
            // 如无任课班级，不继续处理
            $this->display(WX_DIR . DIRECTORY_SEPARATOR . "health_check");
        } else {
            // // 学生班级筛选
            // if($this->get("class_id")) {
            //     $this->params['class_id'] = $data['classId'] = $this->get("class_id");
            // } else {
            //     // 如未筛选某个班级，默认选择第一个班级
            //     $class = $this->teacherClassArr['0'];
            //     $this->params['class_id'] = $data['classId'] = $class['id'];
            // }
            // 用户名称筛选
            if(trim($this->get("keyword"))) $this->keyword = $data['keyword'] = trim($this->get("keyword"));
            if(trim($this->get("createdate"))) $this->createdate = $data['createdate'] = trim($this->get("createdate"));
            // echo '<pre>';var_export(($this->user));exit;
            // var_export($this->get("treatment"));exit;
            // if($this->get("bindusertype") !== NULL && $this->get("bindusertype") !== '') $data['bindusertype'] = $this->get("bindusertype");
            // if($this->get("is_contact") !== NULL && $this->get("is_contact") !== '') $data['is_contact'] = $this->get("is_contact");
            // if($this->get("is_return") !== NULL && $this->get("is_return") !== '') $data['is_return'] = $this->get("is_return");
            // if($this->get("is_detained") !== NULL && $this->get("is_detained") !== '')  $data['is_detained'] = $this->get("is_detained");
            // if($this->get("current_status") !== NULL && $this->get("current_status") !== '') $data['current_status'] = $this->get("current_status");
            // if($this->get("family_status") !== NULL && $this->get("family_status") !== '') $data['family_status'] = $this->get("family_status");
            // if($this->get("treatment") !== NULL && $this->get("treatment") !== '') $data['treatment'] = $this->get("treatment");
            // if($this->get("symptom") !== NULL && $this->get("symptom") !== '') $data['symptom'] = $this->get("symptom");
            // if($this->get("begin_time") !== NULL && $this->get("begin_time") !== '') $data['begin_time'] = $this->get("begin_time");
            // if($this->get("end_time") !== NULL && $this->get("end_time") !== '') $data['end_time'] = $this->get("end_time");

            // 每页10个
            $data['pageStart'] = $this->get('start') ? $this->get('start') : 0;
            $data['pageSize']= 10;

            $data['join_student'] = 1;
            $data['schoolId'] = $this->user['school_id'];
            // 只获取学生
            $data['bindusertype'] = BIND_TYPE_STUDENT;
            // 按id倒序
            $data['orderBy'] = '`createtime` DESC';
            $healthList = $this->wxUserModel->get_wx_user_health_list($data);
            // 获取其他信息
            $healthData = get_health_const_data();
            foreach($healthList as &$health) {
                $health['current_status'] = $healthData['current_status'][$health['current_status']];
                $health['family_status'] = $healthData['family_status'][$health['family_status']];
                $health['treatment'] = $healthData['treatment'][$health['treatment']];
                $health['is_return'] = $health['is_return'] ? '是' : '否';
                $health['is_contact'] = $health['is_contact'] ? '是' : '否';
                $health['is_detained'] = $health['is_detained'] ? '是' : '否';
                $health['holiday_dest'] = $health['holiday_dest'] ? $health['holiday_dest'] : '无';
                // 获取症状数组
                $symptomkeyArr = explode(',', $health['symptom']);
                // 获取症状字符数组
                $symptomArr = array();
                if($symptomkeyArr) {
                    foreach($symptomkeyArr as $symptomkey) {
                        if($symptomkey) {
                            array_push($symptomArr, $healthData['symptom'][$symptomkey]);
                        }
                    }
                    $health['symptom'] = implode(',', $symptomArr);
                }
                $health['symptom'] = $health['symptom'] ? $health['symptom'] :'自觉正常';  
            }
            $this->healthList = $healthList;
            // echo '<pre>';var_export(($healthList));exit;
            $this->display(WX_DIR . DIRECTORY_SEPARATOR . "health_check");
        }  
    }
    // 获取更多健康
    public function  get_class_health_list() {
        $page = $this->get('page');
        // 每页10个
        $data['pageStart'] = ($page - 1) * 10;
        $data['pageSize']= 10;
        // $data['pageStart'] = ($page - 1) *3;
        // $data['pageSize']= 3;
        $data['classId'] = $this->get("class_id");
        if(trim($this->get("keyword"))) $data['keyword'] = trim($this->get("keyword"));
        $data['join_student'] = 1;
        $data['schoolId'] = $this->user['school_id'];
        // 只获取学生
        $data['bindusertype'] = BIND_TYPE_STUDENT;
        // 按id倒序
        $data['orderBy'] = '`createtime` DESC';
        $healthList = $this->wxUserModel->get_wx_user_health_list($data);
        // 获取其他信息
        $healthData = get_health_const_data();
        foreach($healthList as &$health) {
            $health['current_status'] = $healthData['current_status'][$health['current_status']];
            $health['family_status'] = $healthData['family_status'][$health['family_status']];
            $health['treatment'] = $healthData['treatment'][$health['treatment']];
            $health['is_return'] = $health['is_return'] ? '是' : '否';
            $health['is_contact'] = $health['is_contact'] ? '是' : '否';
            $health['is_detained'] = $health['is_detained'] ? '是' : '否';
            $health['holiday_dest'] = $health['holiday_dest'] ? $health['holiday_dest'] : '无';
            // 获取症状数组
            $symptomkeyArr = explode(',', $health['symptom']);
            // 获取症状字符数组
            $symptomArr = array();
            if($symptomkeyArr) {
                foreach($symptomkeyArr as $symptomkey) {
                    if($symptomkey) {
                        array_push($symptomArr, $healthData['symptom'][$symptomkey]);
                    }
                }
                $health['symptom'] = implode(',', $symptomArr);
            }
            $health['symptom'] = $health['symptom'] ? $health['symptom'] :'自觉正常';
            $health['headimgurl'] = $health['headimgurl'] ? $health['headimgurl'] : $this->staticWxUrl . 'assets/img/head.png'; 
        }
        exit(json('', true, $healthList));
    }

    // 卡号激活页面
    public function activate_card() {
        $this->htmlTitle = '卡号激活——' . $this->user['realname'];
        // 检查是否已激活过
        $studentInfo = $this->schoolModel->get_student_info($this->user['id']);
        if($studentInfo['expire_date'] && $studentInfo['expire_date'] > date('Y-m-d', strtotime('+7 day'))) {
            echo '<h1 style="font-size: 0.6rem;">' . $studentInfo['realname'] . '账号已激活，无需重复激活</h1>';exit;
        }
 
        // 获取收费项
        $data['isDelete'] = 0;
        $data['schoolId'] = $this->user['school_id'];
        $chargeList = $this->schoolModel->get_charge_list($data);
        foreach($chargeList as $key => $charge) {
            $effectTimeBegin = $charge['effect_time_begin'];
            $effectTimeEnd = $charge['effect_time_end'];
            // 判断收费有效时间
            if($charge['effect_mode'] == CHARGE_EFFECT_TYPE_LONG || ($effectTimeBegin <= date('m-d') && $effectTimeEnd >= date('m-d'))) {
                if($charge['active_mode'] == CHARGE_ACTIVE_TYPE_MONTH) {
                    $month = $charge['active_month'];
                    $expireDate = $this->user['expire_date'];
                    if(empty($expireDate) || $expireDate < date('Y-m-d')) {
                        $expireDate = date('Y-m-d');
                    }
                    $chargeList[$key]['activeDate'] = date("Y-m-d", strtotime("+" . $month . " months", strtotime($expireDate)));
                } else {
                    // 日期改成自带年级了
                    // $chargeList[$key]['activeDate'] = date('Y') . '-' . $charge['active_time'];
                    $chargeList[$key]['activeDate'] = $charge['active_time'];
                }
            } else {
                unset($chargeList[$key]);
            }
        }
        $this->chargeList = $chargeList;
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . "activate_card");
    }

    public function pay($chargeId) {
        $this->htmlTitle = '卡号激活——' . $this->user['realname'];
        // 检查是否已激活过
        $studentInfo = $this->schoolModel->get_student_info($this->user['id']);
        if($studentInfo['expire_date'] && $studentInfo['expire_date'] > date('Y-m-d', strtotime('+7 day'))) {
            echo '<h1>' . $studentInfo['realname'] . '账号已激活，无需重复激活</h1>';exit;
        }

        // 获取jssdk参数
        $this->load->library('wechat');
        $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        $this->dataJssdk = $this->wechat->jssdk_data($url);

        // 获取jssdk参数
        $this->load->library('wechat');
        $openid = $this->session->userdata['wx']['openid'];
        // $outTradeNo = md5(uniqid());
        $outTradeNo = date("YmdHis") . mt_rand(100000, 999999);
        // 获取收费项详情
        $charge = $this->schoolModel->get_charge_info($chargeId);
        $price = $charge['price'];
        // var_export($price);exit;
        $body = $charge['name'];
        $res = $this->wechat->unifiedorder($body, $outTradeNo, $price * 100, wx_url('wxpaynotify/card'), 'JSAPI', $openid);
        if(!isset($res['prepay_id'])) {
            echo '<h1>系统错误，暂不支持支付功能</h1>';exit;
        }
        $prepayId = $res['prepay_id'];
        $data = $this->wechat->get_webpay_param($prepayId);
        $this->data = $data;
        // 插入订单
        $this->db->insert(WxUserModel::$chargePayTable, array(
            'school_id' => $this->user['school_id'],
            'charge_id' => $chargeId,
            'out_trade_no' => $outTradeNo,
            'student_id' => $this->user['id'],
            'openid' => $openid,
            'price' => $price,
            'is_paid' => 0,
            'expire_date' => $this->get('expire_date'),
            'createtime' => date('Y-m-d H:i:s')
        ));
        // var_export($this->data);exit;
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . "wx_pay");
    }
}